<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Sqlite</title>
</head>
<body onload="init()">
    <!-- 创建数据库对象、使用事务进行数据库操作 -->
    姓名：<input type="text" id="name"/>
    电话：<input type="text" id="tel" />
    <input type="button" value="保存" onclick="saveData()" />
    <hr/>
    <input type="button" onclick="showAllData()" value="显示全部">
            <input type="button" onclick="delAllData()" value="清空全部">
    <hr/>
    <table id="datatable" border="1">

    </table>
    <p id="'msg"></p>

</body>
<script type="text/javascript">
    var datatable = null;
    var db = openDatabase('myTel','1.0','test db',1024*100);//数据库名 版本 数据库描述 大小

    function init(){//初始化工作
        datatable = document.getElementById('datatable');
        showAllData();
    }
    function removeAllData(){//移除页面上展示的数据
        for(var i = datatable.childNodes.length-1;i>=0;i--){
            datatable.removeChild(datatable.childNodes[i]);
        }
        var tr = document.createElement('tr');
        var th1 = document.createElement('th');
        var th2 = document.createElement('th');
        th1.innerHTML = '姓名';
        th2.innerHTML = '电话';
        tr.appendChild(th1);
        tr.appendChild(th2);
        datatable.appendChild(tr);

    }
    function showData(row){//显示数据
        var tr = document.createElement('tr');
        var td1 = document.createElement('td');
        td1.innerHTML = row.name;
        var td2 = document.createElement('td');
        td2.innerHTML = row.tel;
        tr.appendChild(td1);
        tr.appendChild(td2);
        datatable.appendChild(tr);
    }
    function showAllData(){//显示所有数据

        db.transaction(function (tx){
            tx.executeSql('create table if not exists TelData(name TEXT,tel TEXT)',[],function(tx,res){

                },function(tx,err){
                    alert(err.message)
                });

            tx.executeSql('select * from TelData',[],function(tx,result){
                removeAllData();
                for(var i = 0 ;i<result.rows.length;i++){
                    showData(result.rows.item(i));
                }
            })
        })
    }
    function saveData(){//保存数据
        var name = document.getElementById('name').value;
        var tel = document.getElementById('tel').value;
        addData(name,tel);
        showAllData();
    }
    function addData(name,tel){//添加数据
        db.transaction(function(tx){
            tx.executeSql('insert into TelData values(?,?)',[name,tel],function(tx,rs){
                alert('yes');
            },
            function (tx,err){
                alert(err.source +'===='+err.message);
            })
        })
    }
    function  delAllData(){//删除所有数据
        db.transaction(function(tx){
            tx.executeSql('delete from TelData',[],function(tx,res){
                alert('删除成功~');
            },function (tx,err){
                alert('删除失败'+err.message);
            })
        })
        showAllData();
    }
</script>
</html>